// main.go
package main

import (
	"fmt"
	"log"
	"net/url"
	"os"
	"strings"

	"gitee.com/yangboies/godownloader"
)

var (
	printI         int
	outputFilename string = "a.out"
	durl           *url.URL
)

func init() {
	if len(os.Args) < 2 {
		log.Fatalln("use `command url [output]`")
	}

	var err error
	durl, err = url.Parse(os.Args[1])
	if err != nil {
		log.Fatalln("url error:", err, "\nPlase use `command url [output]`")
	}
}

func main() {
	d, err := godownloader.NewHttpDownloadFile(durl.String(), nil, outputFilename)
	if err != nil {
		fmt.Println(err)
	}

	d.SetSizeCall(func(d *godownloader.Downloader) {
		printI++
		if d.GetContentLength() == -1 {
			fmt.Printf("\r size:%d [?]%s", d.GetAlreadySize(), strings.Repeat(".", printI%3+1))
		} else {
			i := float64(d.GetAlreadySize()) / float64(d.GetContentLength()) * 100
			lines := strings.Repeat("=", int(i)/2) + strings.Repeat(" ", (50-int(i)/2))
			fmt.Printf("\r%.0f%%[%s]%s", i, lines, strings.Repeat(".", printI))
		}
	})

	err = d.Run()
	if err != nil {
		log.Fatalln("\nfailed:", err)
	} else {
		fmt.Println("\nsucess, size:", d.GetContentLength())
	}
}
